import 'package:casdon/common/service/tuya_service.dart';
import 'package:casdon/core/auth/auth_storage.dart';
import 'package:casdon/core/logger/log.dart';
import 'package:casdon/modules/home/providers/home_provider.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

class TuyaAuthNotifier extends AsyncNotifier<void> {
  @override
  void build() {
    // 不用 async，不用 await
    _checkLoginState();
  }

  Future<void> _checkLoginState() async {
    final ret = await TuyaService().isloggedIn;
    ref.read(tuyaLoginStateProvider.notifier).update((_) => ret);
    state = const AsyncValue.data(null);
  }

  Future<void> login() async {
    if (state.isLoading) return;

    try {
      final useCase = ref.read(authUserInfoUsecaseProvider);
      final authUserInfo = await useCase.execute();

      if (authUserInfo == null) {
        throw Exception("用户鉴权信息为null");
      }

      final authStorage = ref.read(authStorageProvider.notifier);
      await authStorage.saveUserAccount(authUserInfo.userName);
      await authStorage.savePwd(authUserInfo.password);
      await authStorage.saveNickName(authUserInfo.nickName);
      await authStorage.saveUserId(authUserInfo.userId);

      var ret = false;
      Object? lastError;
      for (var attempt = 1; attempt <= 3 && !ret; attempt++) {
        try {
          ret = await TuyaService().login(
            authUserInfo.userName,
            authUserInfo.password,
          );
        } on PlatformException catch (e, st) {
          lastError = e;
          Log.e('涂鸦登录失败: 第$attempt次', e, st);
          if (attempt >= 3) rethrow;
        }
      }

      if (!ret) {
        throw lastError ?? Exception("涂鸦登录失败");
      }
      Log.i("涂鸦登录 结果：$ret");
      ref.read(tuyaLoginStateProvider.notifier).update((_) => ret);

      state = const AsyncValue.data(null);
    } catch (e, st) {
      Log.e("登录失败: $e", e, st);
      ref.read(tuyaLoginStateProvider.notifier).update((_) => false);
      state = AsyncValue.error(e, st);
    }
  }

  Future<void> logOut() async {
    if (state.isLoading) return;
    state = const AsyncValue.loading();
    state = await AsyncValue.guard(() async {
      final ret = await TuyaService().logOut();
      state = AsyncValue.data(null);
      ref.read(tuyaLoginStateProvider.notifier).update((_) => !ret);
    });
  }
}

final tuyaLoginProvider = AsyncNotifierProvider<TuyaAuthNotifier, void>(
  () => TuyaAuthNotifier(),
);
// 涂鸦登录状态
final tuyaLoginStateProvider = StateProvider<bool>((ref) => false);
